<template>
	<form ref="formRef" id="data-form-container" @submit.prevent="handleSubmit" class="data-form-container">
		<div class="form-item">
			<div class="input-area">
				<input
					id="nickname"
					name="nickname"
					type="text"
					v-model="data.nickname"
					maxlength="10"
					placeholder="用户昵称"
				/>
				<span class="word-limit">{{ data.nickname.length }}/10</span>
			</div>
		</div>
		<div class="form-item">
			<div class="text-area">
				<textarea
					name="content"
					id="content"
					maxlength="300"
					v-model="data.content"
					:style="{ resize: 'none', height: '150px' }"
					placeholder="输入内容"
				></textarea>
				<span class="word-limit">{{ data.content.length }}/300</span>
			</div>
		</div>
		<div class="form-item">
			<button class="subButton" type="submit" :class="{ disabled: isSubmiting }" :disabled="isSubmiting">
				{{ isSubmiting ? '提交中...' : '点击提交' }}
			</button>
			<span class="err">{{ msg }}</span>
		</div>
	</form>
</template>

<script>
export default {
	name: 'DataForm',
	emits: ['submit'],
	data() {
		return {
			data: {
				nickname: '',
				content: '',
			},
			msg: '',
			isSubmiting: false, // button是否添加禁用样式
		}
	},
	methods: {
		handleSubmit() {
			if (!this.data.nickname) {
				this.msg = '昵称不能为空'
				return
			}
			if (!this.data.content) {
				this.msg = '内容不能为空'
				return
			}
			this.isSubmiting = true
			this.msg = ''
			// 提交事件
			this.$emit('submit', this.data, (msg) => {
				this.isSubmiting = false
				this.$showMessage({
					content: msg,
					type: 'success',
					duration: 2000,
					container: this.$refs.formRef,
				})
				this.data.nickname = ''
				this.data.content = ''
			})
		},
	},
}
</script>

<style lang="less" scoped>
@import '~@/styles/basic/var.less';
.data-form-container {
	width: 100%;
	font-size: 14px;
	input,
	textarea {
		width: 100%;
		padding: 15px 15px;
		font-size: inherit;
		outline: none;
		border: 1.5px dashed @gray;
		border-radius: 5px;
		&:focus {
			border: 1.5px dashed @primary;
		}
	}
	textarea {
		width: 100%;
		font-family: '微软雅黑';
		overflow-y: auto;
	}
	.form-item {
		margin: 20px 0;
		.input-area,
		.text-area {
			display: block;
			position: relative;
			.word-limit {
				font-size: 0.8rem;
				position: absolute;
				right: 5px;
				bottom: 5px;
				color: @gray;
				user-select: none;
			}
		}
		.input-area {
			width: 50%;
			.word-limit {
				bottom: 2px;
			}
		}
		.subButton {
			width: 100px;
			height: 40px;
			border: none;
			border-radius: 5px;
			color: #fff;
			background-color: @primary;
			cursor: pointer;
			transition: all 0.3s;
			&:hover {
				filter: brightness(120%);
			}
			&.disabled {
				cursor: not-allowed;
				background-color: lighten(@primary, 20%);
				&:hover {
					filter: brightness(100%);
				}
			}
		}
		.err {
			margin-left: 10px;
			color: @critical;
			user-select: none;
		}
	}
}
</style>
